﻿using Dapper;
using Kele.Activity.Core;
using Kele.Activity.Helper;
using Kele.Activity.Models;
using Kele.Repository;
using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using Senparc.CO2NET.Helpers;
using SqlKata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kele.Activity.Service
{
    public partial class ActivityService
    {
        public async Task<dynamic> H5_GetActivityDetailAsync(string user_id, int Id)
        {


            var query = new Query().Where("id", Id);


            var entity = await AppRepository.FirstOrDefaultAsync<ActivityEntity>(Id);

            var form = await AppRepository.FirstOrDefaultAsync<Form>("FormId", entity.FormId);

            var skinList = await GetSkinListAsync();
            var skin = skinList.FirstOrDefault(s => s.Id == entity.SkinId);

            var registers = (await AppService.Record.GetRecordListAsync(Id)).ToList();
            var record = await AppService.Record.GetRecordByUserIdAsync(Id, user_id);
            var merchant = await MerchantEngine.GetMerchantAsync(entity.MerchantId);
            dynamic attrs = new JObject();
            //TODO
            attrs.isOutOfStock = false; //名额已满
            attrs.isCollection = false;
            attrs.isPromoted = false;
            //attrs.registers = registers;
            attrs.useShareImageComponent = true;
            attrs.drawShareImageByServer = true;
            attrs.alreadyRegister = false;
            attrs.showPrePrice = true;
            attrs.payAll = false;
            attrs.requiredPay = true;
            attrs.limitPerPerson = 1;
            attrs.shareTitle = "智慧喵免费体验课";
            attrs.shareLink = "https://8da1b6bc0000d0ce.wx.quickbass.cn/?f=11&page=detail";
            var data = new
            {
                t = DateTimeHelper.GetUnixDateTime(DateTime.Now),
                form?.Key,
                form?.Alias,
                form?.Slogan,
                //setting = string.IsNullOrWhiteSpace(skin.setting) ? new JObject() : JObject.Parse(skin.setting)
                skin = new
                {
                    skin?.Id,
                    skin?.Alias,
                    setting = skin?.Setting.ToJObject()
                },
                activity_id = entity.Id, //活动ID
                entity.Title,
                entity.Rule,
                entity.Description,
                images = Enumerable.Select(entity.Images.ToJArray(), image => (string)image["url"]),
                entity.IsRecommend,
                entity.StartTime,
                entity.EndTime,
                top_images = Enumerable.Select(entity.TopImages.ToJArray(), image => (string)image["url"]),
                bgm_url = entity.MusicId,
                entity.Status, //活动已下线
                fields = entity.Fields.ToJArray(),
                props = entity.Props.ToJObject(),
                stores = entity.Stores.ToJArray(),
                entity.BrowseNum,
                entity.SoldNum,
                entity.BuyerNum,
                entity.ShareNum,
                entity.RemainNum,
                entity.Price,
                entity.PrePrice,
                entity.LimitPerPerson,
                attrs
            };

            return new
            {
                data,
                merchant,
                record
            };
        }

        public async Task<dynamic> H5_GetActivityListAsync(int take = 10, int skip = 0)
        {


            var paginationResult = await AppRepository.PaginateAsync<ActivityEntity>(skip, take);
            var total = paginationResult.Count;
            var list = paginationResult.List;

            var formList = await AppService.Form.GetFormListAsync();

            var data = new List<dynamic>();
            foreach (var item in list)
            {
                var form = formList.First(f => f.Id == item.FormId);
                var merchant = await MerchantEngine.GetMerchantAsync(item.MerchantId);
                data.Add(new
                {
                    activity_id = item.Id,
                    item.MerchantId,
                    form?.Key,
                    form?.Alias,
                    merchant_name = merchant.name,
                    merchant_avatar = merchant.avatar,
                    item.Title,
                    top_images = item.TopImages.ToJArray().Select(image => image["thumbUrl"]?.Value<string>()?? image),
                    item.BrowseNum,
                    item.SoldNum,
                    item.ShareNum,
                    item.BuyerNum,
                    item.RemainNum,
                    item.Price,
                    item.PrePrice,
                    timestamp = DateTimeHelper.GetUnixDateTime(DateTime.Now),
                });
            };


            return new { total, data };
        }

        public async Task<dynamic> LoadActivityVoucherAsync(string openid, string activity_id)
        {
            using (var connection = new MySqlConnection())
            {
                connection.Open();
                var sql = new StringBuilder();
                sql.Append(" SELECT * FROM kl_view_activity WHERE activity_id=@activity_id;");
                sql.Append(" SELECT `name`,mobile, pay_time, num, total_fee from kl_activity_record where activity_id=@activity_id and openId=@openid;");

                using (var multi = await connection.QueryMultipleAsync(sql.ToString(), new { activity_id, openid }))
                {
                    var ac = await multi.ReadSingleOrDefaultAsync();
                    var records = await multi.ReadAsync();
                    var merchant_id = ac.merchant_id;

                    sql.Clear();
                    sql.Append(" select * from kl_merchant_store   where merchant_id=@merchant_id ");
                    var stores = (await connection.QueryAsync(sql.ToString(), new { merchant_id })).ToArray();

                    var merchant = new
                    {
                        ac.merchant_id, //商户ID
                        nick = ac.merchant_name, //商户名称
                        avatar = ac.merchant_logo,
                        stores,
                        store_count = stores.Length,
                        vip_info = "c",//用户的全站vip信息，可取值如下：c(普通会员),asso_vip(荣誉会员)，vip1,vip2,vip3,vip4,vip5,vip6(六个等级的正式vip会员)，共8种取值，其中asso_vip是由vip会员衰退而成，与主站上的vip0对应。
                        isMerchantExpired = false, //商家账户过期
                        promoted_type = "not authentication", //有无实名认证。可选值:authentication(实名认证),not authentication(没有认证)
                        status = "normal",//状态。可选值:normal(正常),inactive(未激活),delete(删除),reeze(冻结),supervise(监管)
                        is_golden_seller = "true",//用户是否是金牌卖家
                        seller_credit = new //卖家信用
                        {
                            level = 1,
                            score = 100,
                            total_num = 100,
                            good_num = 100
                        },
                        type = "B",//用户类型。可选值:B(B商家),C(C商家)
                        has_go_home = false,//是否允许跳转到商家主页
                        tags = ac.merchant_tags.Split(","),//商家标签
                    };

                    return new
                    {
                        records,
                        merchant,
                        qrCode = AppUtility.GetBase64QRCode("dddd")
                    };
                }
            }
        }

    }
}